package org.zhxy.core.system.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.mybatis.spring.mapper.MapperFactoryBean;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.zhxy.common.config.MapperFactory;
import org.zhxy.common.response.PageResult;
import org.zhxy.common.response.Result;
import org.zhxy.common.response.ResultCode;
import org.zhxy.common.utils.CollectionUtils;
import org.zhxy.common.utils.Constants;
import org.zhxy.entity.system.Permission;
import org.zhxy.entity.system.Role;
import org.zhxy.entity.system.RolePermission;
import org.zhxy.entity.system.UserRole;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional
public class RoleService {

    public PageResult<Role> getRoleList(Map<String, Object> map) {
        Integer page = Integer.parseInt(map.get(Constants.Blanket.PAGE).toString());
        Integer size = Integer.parseInt(map.get(Constants.Blanket.SIZE).toString());
        IPage<Role> iPage = new Page<>(page,size);
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(map.get(Constants.DB.NAME))) queryWrapper.like(Constants.DB.NAME,map.get(Constants.DB.NAME).toString());
        queryWrapper.orderByDesc(Constants.DB.NAME);
        IPage<Role> result = MapperFactory.roleMapper.selectPage(iPage, queryWrapper);
        if(CollectionUtils.checkCollection(result.getRecords())){
            for (Role role : result.getRecords()) {
                List<Permission> permissions = MapperFactory.permissionMapper.getPermissionListByRoleId(role.getId());
                role.setPermissions(new HashSet<>(permissions));
            }
        }
        return new PageResult<Role>(result.getTotal(),result.getRecords());
    }

    public Result saveRole(Role role) {
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(Constants.DB.NAME,role.getName());
        Role target = MapperFactory.roleMapper.selectOne(queryWrapper);
        if(!StringUtils.isEmpty(target)) return new Result(ResultCode.DATA_IS_EXIST);
        if(role.getPermissionIds().split(Constants.Sign.COMMA).length == Constants.Number.ZERO)
            return new Result(ResultCode.SYSTEM_ACCESS_ROLE_NO_HAS_PERMISSION);
        MapperFactory.roleMapper.insert(role);
        for (String permissionId : role.getPermissionIds().split(Constants.Sign.COMMA)) {
            RolePermission rolePermission = RolePermission.builder().permissionId(permissionId).roleId(role.getId()).build();
            MapperFactory.rolePermissionMapper.insert(rolePermission);
        }
        return Result.SUCCESS();
    }

    public Result updateRole(Role role) {
        Role target = MapperFactory.roleMapper.selectById(role.getId());
        BeanUtils.copyProperties(role,target);
        MapperFactory.roleMapper.updateById(target);
        QueryWrapper<RolePermission> rolePermissionQueryWrapper = new QueryWrapper<>();
        rolePermissionQueryWrapper.eq(Constants.DB.COLUMN_ROLE_ID,role.getId());
        List<RolePermission> rolePermissions = MapperFactory.rolePermissionMapper.selectList(rolePermissionQueryWrapper);
        if(CollectionUtils.checkCollection(rolePermissions))
            MapperFactory.rolePermissionMapper.deleteBatchIds(rolePermissions.stream().map(RolePermission::getId).collect(Collectors.toList()));
        for (String permissionId : role.getPermissionIds().split(Constants.Sign.COMMA))
            MapperFactory.rolePermissionMapper.insert(RolePermission.builder().permissionId(permissionId).roleId(role.getId()).build());
        return Result.SUCCESS();
    }



    public Result removeRole(String id) {
        List<Permission> permissions = MapperFactory.permissionMapper.getPermissionListByRoleId(id);
        if(CollectionUtils.checkCollection(permissions))
            return new Result(ResultCode.SYSTEM_ACCESS_ROLE_HAS_PERMISSION);
        QueryWrapper<RolePermission> rolePermissionQueryWrapper = new QueryWrapper<>();
        rolePermissionQueryWrapper.eq(Constants.DB.COLUMN_ROLE_ID,id);
        List<RolePermission> rolePermissions = MapperFactory.rolePermissionMapper.selectList(rolePermissionQueryWrapper);
        if(CollectionUtils.checkCollection(rolePermissions))
            return new Result(ResultCode.SYSTEM_ACCESS_ROLE_HAS_PERMISSION);
        MapperFactory.roleMapper.deleteById(id);
        return Result.SUCCESS();
    }

    public Object findAll() {
        return MapperFactory.roleMapper.selectList(null);
    }

    public Result saveOrUpdateUserRole(Map<String, Object> map) {
        String userId = map.get(Constants.Parameters.USER_ID).toString();
        String roleIds = map.get(Constants.Parameters.ROLE_IDS).toString();
        QueryWrapper<UserRole> userRoleQueryWrapper = new QueryWrapper<>();
        userRoleQueryWrapper.eq(Constants.DB.COLUMN_USER_ID,userId);
        List<UserRole> userRoles = MapperFactory.userRoleMapper.selectList(userRoleQueryWrapper);
        if(CollectionUtils.checkCollection(userRoles))
            MapperFactory.userRoleMapper.deleteBatchIds(userRoles.stream().map(UserRole::getId).collect(Collectors.toList()));
        for (String roleId : roleIds.split(Constants.Sign.COMMA))
            MapperFactory.userRoleMapper.insert(UserRole.builder().roleId(roleId).userId(userId).build());
        return Result.SUCCESS();
    }
}
